<?php
namespace Admin\Model;
use Think\Model;
use Think\Exception;

// use Admin\Model\Users;

class ScoreTranModel extends Model {
    protected $error = null;
    protected $msg   = '';

    //积分异动操作方法
    /*
     * $busid:异动类型
     * $uid:用户id
     * $unick:用户名
     * $aid: 账户ID,留空则取默认账户
     * $type: -1:减; 1加
     * $money: 金额
     * $opid: 经办人
     * $channel: 通道
     * $orderId: 订单id
     * $memo: 备注
     * $source: 来源id,用于计算收益来源
     * $sourceUser: 来源,同上
     */
    public function tran($busid, $uid, $type, $score, $memo = '', $opid = '', $channel = 0, $orderId = '',  $source = '', $sourceUser = ''){

        if (empty($uid) || empty($busid)) {
            $this->error = -10;
            return false;
        }

        if (empty($type)) {
            $this->error = -11;
            return false;
        }

         $userData = D('Users')->getById($uid);

        // 判断crc
        if (!$this->checAccountkCRC($userData)) {
            $this->error = -12;
            return false;
        }

        //得到本次变化后的账户积分
        $userData['user_points'] = $userData['user_points'] + $score * $type;

        if(($userData['user_points'] < 0)){
            $this->error = -13;
            return false;
        }

        $userData['score_crc'] = $this->getAccountCRC($userData);

        $data = array(
            'id'      => $lastId,
            'uid'     => $uid,
            'uname'   => $userData['user_name'],
            'businessId'   => $busid,
            'type'    => $type,
            'score'   => $score,
            'balance' => $userData['user_points'],
            'memo'    => $memo,
            'operId'  => $opid,
            'createtime' => getModeltime(),
            'orderId' => $orderId,
            'source' => $source,
            'sourceUser' => $sourceUser
        );


        $lastId = getTimeMarkID();

        $model = new Model();

        try{
            $model->startTrans();

            $newUserData = array(
                'user_points' => $userData['user_points'],
                'score_crc'   => $userData['score_crc'],
            );

            $userInfoSaveRes = $model->table('__USERS__')->data($userData)->where(array('user_id'=>$userData['user_id']))->save();

            if (!$userInfoSaveRes) {
                throw new Exception("修改用户信息修改失败", -21);
            }

            $addLogRes = $model->table('__SCORE_TRAN__')->data($data)->add();

            if (!$addLogRes) {
                throw new Exception("添加异动记录失败", -22);
            }

            $model->commit();
            addlog('修改用户积分' . $uid, '', $userData);
            return true;
        }catch(Exception $e){
            $model->rollback();
            $this->error = $e->getCode();
            $this->msg   = $e->getMessage();
            return false;
        }
    }

    private function getAccountCRC($params){
        $str = $params['user_id']
         .$params['user_points']
         // .ROUND($params['a_freeMoney']*100)
         // .ROUND($params['frozenMoney']*100)
         // .ROUND($params['score']*1000)
         .$params['user_type'];

        return MD5(SHA1($str) . '@EC$^3^&3!#S$9%096%$$^&&le2g3*4H$%#$');

    }

     //加密异动记录,防止篡改
    private function md5Trans($p) {
        $string = implode('@!dE4', array_values($p));
        return MD5(SHA1($string) . $this->crcSalt);
    }

    //检查crc校验数据是否正确
    private function checAccountkCRC($params) {

      // echo $this->getAccountCRC($params);exit;
      if($this->getAccountCRC($params) === $params['score_crc']){
        return true;
      }

      //crc错误,冻结用户
      D('Users')->freezeUser($params['user_id']);
      return false;
    }

    public function getError(){
        return $this->error;
    }


    public function getLogByUid($id){
        if (empty($id)) {
            return false;
        }

        return $this->where(array('uid'=>$id))->order("createtime desc")->select();
    }
}
